package com.qm.utils;

import com.qm.finger.protocol.FingerProtocol;

import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

/**
 * create by steven
 * 2021-06-16
 * <p>
 * des:读取注册指纹信息
 */
public class ReadRegisterUtils {
    private static Timer mTimer;//定时器读取指纹问题
    private static ReadRegisterUtils readTimerUtils;
    private int ret = 0;
    private  FingerListen mFingerListen;
    private InputStream mInputStream;
    private boolean isStop=false;
    public static ReadRegisterUtils getInstance() {
        if (mTimer == null)
            mTimer = new Timer();
        if (readTimerUtils == null) {
            synchronized (ReadRegisterUtils.class) {
                readTimerUtils = new ReadRegisterUtils();
            }
        }
        return readTimerUtils;
    }

    public void closeFinger() {
        if (mTimer!=null){
            mTimer.cancel();
            mTimer=null;
        }
    }
    //开始注册和比对监听串口数据
    public void startRegisterRead( FingerListen fingerListen, InputStream inputStream) {
        this.mFingerListen=fingerListen;
        this.mInputStream=inputStream;
        if (mTimer != null) {
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (!isStop){
                        try {
                            if (mInputStream == null) {
                                mFingerListen.onFail();
                                mTimer.cancel();
                                mTimer = null;
                                return;
                            }
                            int readLen = mInputStream.available();
                            byte[] readData = new byte[readLen];
                            if (readLen > 0 && readLen >= mInputStream.available()) {
                                if (readLen >= readData.length) {
                                    ret = mInputStream.read(readData, 0, readData.length);
                                } else {
                                    ret = mInputStream.read(readData, 0, readLen);
                                }
                                //解析一下数据
                                mFingerListen.onSuccess(FingerProtocol.ParseReadProtocol(readData));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            mFingerListen.onFail();
                            mTimer.cancel();
                            mTimer = null;
                        }
                    }
                }
            }, 20, 20);

        }
    }
}
